#!/usr/bin/env python
# -*- coding: utf8 -*-

try:
    from xml.etree import ElementTree
except:
    from elementtree import ElementTree

from gdata import service
import gdata
import atom
import getopt
import sys

class BloggerException(Exception):
    pass


class Blogger(object):

    app_name = 'PyBlogger'
    version = '0.1'
    server = 'www.blogger.com'
    service_name = 'blogger'
    blogs = {}
    _current_blogid = None

    def __init__(self, email, password):
        # Authenticated using ClientLogin
        self.service = service.GDataService(email, password)
        self.service.source = "%s %s" % (self.app_name, self.version)
        self.service.service = self.service_name
        self.service.server = self.server
        self.service.ProgrammaticLogin()

        # Get the blog ID for the first blog.
        feed = self.service.Get('/feeds/default/blogs')
        for blog in feed.entry:
            self.blogs[self.get_blogid_from_entry(blog)] = {'title': blog.title.text, 'userid': self.get_userid_from_entry(blog), 'blog': blog}

    def get_blogid_from_entry(self, entry):
        blog_id = None
        self_link = entry.GetSelfLink()
        if self_link:
            blog_id = self_link.href.split('/')[-1]
        return blog_id

    def get_userid_from_entry(self, entry):
        user_id = None
        self_link = entry.GetSelfLink()
        if self_link:
            user_id = self_link.href.split('/')[-3]
        return user_id

    def create_post(self, title, content, labels = None, is_draft = True, content_type = 'html', author_name = None):
        entry = gdata.GDataEntry()
        entry.content = atom.Content(content_type, None, content)
        entry.title = atom.Title('text', title)
        if labels and type(labels) == list:
            for label in labels:
                entry.category.append(atom.Category(label, 'http://www.blogger.com/atom/ns#'))
        if author_name:
            entry.author.append(atom.Author(atom.Name(text=author_name)))
        if is_draft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            entry.control = control
        return self.service.Post(entry, '/feeds/' + self.current_blogid + '/posts/full')

    def __get_current_blogid(self):
        if self._current_blogid:
            return self._current_blogid
        elif len(self.blogs) == 1:
            self._current_blogid = self.blogs[self.blogs.keys()[0]]
        else: 
            raise BloggerException('no selected blog')

    def __set_current_blogid(self, value):
        if self.blogs.has_key(value):
            self._current_blogid = value
        else:
            raise BloggerException('no such blog with id: %s' % value)

    current_blogid = property(__get_current_blogid, __set_current_blogid)

    def get_all_posts(self):
        feed = self.service.GetFeed('/feeds/' + self.current_blogid + '/posts/default')
        return feed.entry

    def get_posts_by_label(self, label):
        feed = self.service.GetFeed('/feeds/' + self.current_blogid + '/posts/default/-/' + label)
        return feed.entry

    def get_labels(self):
        retval = []

        for category in self.blogs[self.current_blogid]['blog'].category:
            retval.append(category.term)

        return retval

    def delete_post(self, entry):
        self.service.Delete(entry.GetEditLink().href)



